package mysql

import "gorm.io/gorm"

type Order struct {
	gorm.Model
	UserId  int64   `gorm:"type:int;not null;index:ip_idx commit:'用户ID'"`
	OrderSn string  `gorm:"type:varchar(50);not null;index:ip_idx commit:'订单编号'"`
	Amount  float64 `gorm:"type:decimal(10,2);not null;index:ip_idx commit:'总金额'"`
	Starts  string  `gorm:"type:enum('已支付','未支付');not null;index:ip_idx commit:'支付状态'"`
	Payment string  `gorm:"type:enum('微信','支付宝','红包');not null;index:ip_idx commit:'支付方式'"`
}
type OrderGoods struct {
	gorm.Model
	OrderId int64   `gorm:"type:int;not null;index:ip_idx commit:'订单ID'"`
	GoodsId int64   `gorm:"type:int;not null;index:ip_idx commit:'商品ID'"`
	Title   string  `gorm:"type:varchar(20);not null;index:ip_idx commit:'商品标题'"`
	Price   float64 `gorm:"type:decimal(10,2);not null;index:ip_idx commit:'商品价格'"`
	Cover   string  `gorm:"type:varchar(255);not null;index:ip_idx commit:'商品封面'"`
	Stock   int64   `gorm:"type:int;not null;index:ip_idx commit:'商品库存'"`
	Starts  string  `gorm:"type:enum('已上架','未上架');not null;index:ip_idx commit:'商品状态'"`
}

func CreateAnimals(o *Order, og *OrderGoods) error {
	// 再唠叨一下，事务一旦开始，你就应该使用 tx 处理数据
	tx := DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	if err = tx.Error; err != nil {
		return err
	}

	if err = tx.Create(&o).Error; err != nil {
		tx.Rollback()
		return err
	}

	if err = tx.Create(&og).Error; err != nil {
		tx.Rollback()
		return err
	}

	og.OrderId = int64(o.ID)

	return tx.Commit().Error
}
